<?php namespace Common\Model;
use Hdphp\Model\Model;

class Cate extends Model{
	
	protected $table = "360mall_category";
	protected $validate = array(
	   array("cate_name","required","请输入分类名称",3,3),
	   array("cate_name","maxlen:30","分类名称不能超过30个字符",3,3),
	   array("cate_sort","num:0,40000","排序必须为数字",3,3),
	);
	
	//添加
	public function store(){
		if(!$this->create()) return false;
		$this->add();
		return true;
	}
	//添加子类
	public function addSon(){
		if(!$this->create()) return false;
		$this->add();
		return true;		
	}
	//获得除了自己以及自己的所有子集
	public function getCatedata($cate_id){
		//1.获得除了自己的所有子集
		$cids = $this->getSon($this->get(),$cate_id);
		$cids[]=$cate_id;
		//将数组转成字符串
		$cids = implode(",", $cids);
		//获得不在cids中$cate_id
		$data = $this->where("cate_id not in ($cids)")->get();
		return  Data::tree($data,"cate_name",$fieldPri = "cate_id",$fieldPid ="cate_pid");
	}
	  //获取子集
	  public function getSon($data,$cate_id){
	  	//静态变量为了防止结果不被覆盖
		 static $temp = array();
		 foreach ($data as $key => $v) {
		 	//条件成立的时候，当前这一条就是$cate_id这一条的子集
		 	if($cate_id==$v['cate_pid']){
		 		$temp[] = $v['cate_id'];
				//递归找子集
				$this->getSon($data,$v['cate_id']);
			}
		}
		return $temp;
	  }
	//编辑分类
	public function edit(){
		if(!$this->create()) return false;
		$this->save();
		return true;	
	} 
	//删除分类
	public function del($cate_id){
	 //获得要删除数据的cate_pid让他的儿子的cate_pid变成自己的cate_pid
	 $cate_pid = $this->where("cate_id",$cate_id)->pluck("cate_pid");
	 //执行修改cate_pid
	 $this->where("cate_pid",$cate_id)->update(array("cate_pid"=>$cate_pid));
	 //执行删除
	 $this->where("cate_id",$cate_id)->delete();
	
	}
}